<?php
namespace Mp\Service\Widget;
use Illuminate\Contracts\Support\Renderable;

class Select extends Input{

	protected $name = 'select';

	protected $source = [];

	protected $view = 'Mp::widgets.select';

	const BEFORE = 'before';

	const BEHIND = 'behind';


	protected function _init($params){
		$this->data = [
			'name' => $this->name,
			'source' => $this->source,
		];
	}

	public function render($params = []){

		return parent::render();
	}

	public function option($params = [],$type = 'before'){
		$option = [
			'value' => $params['value'],
			'selected' => false,
			'label' => $params['label'] ?? 'option',
		];
		//追加
		if($type == self::BEHIND){
			array_push($this->source , $option);
		}elseif($type ==  self::BEFORE){
			//插入前面
			array_unshift($this->source , $option);
		}
		
		$this->data['source'] = $this->source;
		return $this;
	}

	public function selected($value){
		foreach($this->data['source'] as &$val){
			if($val['value'] == $value){
				$val['selected'] = true;
				break;
			}
		}
		return $this;
	}

	public function default($params){
		$this->option($params,self::BEFORE);
		return $this;
	}
}